<?php
require_once dirname(__FILE__) . '/common.inc.php';
require_once dirname(__FILE__) . "/DbUtils.class.php";
require_once dirname(__FILE__) . "/includes/MiscUtils.class.php";
require_once dirname(__FILE__) . "/libs/djpate/phpDocx.php";

$transaction_no = MiscUtils::getParam('i', NULL);
$template_plugin = 'invctmpl';
$myPdo = DbUtils::createPdoInst();

$cond_vals = new stdClass();
$cond_vals->c = 't.transaction_no = :v1';
$cond_vals->v = array(':v1' => $transaction_no);
$result = DbUtils::get($myPdo, 'pz_sys_module_data_transaction', $cond_vals, NULL, NULL, NULL, NULL, NULL);
if (count($result->d) != 1) {
  die('No Transaction Found');
}
$data = $result->d[0];
$sql = 'SHOW COLUMNS FROM pz_sys_module_data_transaction';
$stmt = $myPdo->prepare($sql);
$column_names = array();
$column_types = array();
try {
  if($stmt->execute()){
    $raw_column_data = $stmt->fetchAll();
    foreach($raw_column_data as $outer_key => $array){
      foreach($array as $inner_key => $value){
        if ($inner_key === 'Field'){
          if (!(int)$inner_key){
            $column_names[] = $value;
          }
        }
        if ($inner_key === 'Type'){
          if (!(int)$inner_key){
            $column_types[] = $value;
          }
        }
      }
    }
  }
} catch (Exception $e){
  die('Error occurs while accessing database');
}

$result = DbUtils::get($myPdo, 'pz_sys_plugin_' . $template_plugin . '_files', NULL, NULL, NULL, NULL, NULL, NULL);
if (count($result->d) != 1) {
  die('No Invoice Template');
}
$obj = $result->d[0];
$path = 'ext/plugin/bin/' . $template_plugin . '/uploads/' . $obj->name_on_server;

if (!file_exists($path)) {
  echo 'File not found in hard drive';
  exit;
} else {
  $not_good = '</w:t></w:r></w:p><w:p w:rsidRDefault="00A25190" w:rsidP="005B7FF8"><w:pPr><w:pStyle w:val="NoSpacing"/><w:rPr><w:b/></w:rPr></w:pPr><w:r><w:rPr><w:b/></w:rPr><w:t>';
  $phpdocx = new phpdocx($path);
  setlocale(LC_ALL, 'en_NZ');
  foreach ($column_names as $idx => &$column_name) {
    if (isset($column_types[$idx]) && $column_types[$idx] == 'datetime') {
      $data->$column_name = date('Y-m-d', strtotime($data->$column_name));
    }
    if (isset($column_types[$idx]) && $column_types[$idx] == 'decimal(10,2)') {
      $data->$column_name = str_replace('$', '', MiscUtils::money_format('%n', $data->$column_name));
    } 
    if ($column_name == 'fee_description') { 
      $data->$column_name = str_replace('<br />', $not_good, nl2br($data->$column_name));
    }
    $phpdocx->assign("#$column_name#", $data->$column_name);
  }
  $phpdocx->download("INVOICE$transaction_no.docx");
  exit;
}
?>